package com.innovation.chengzhangriji.ui.widget;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.util.FileUtils;

import java.util.ArrayList;

public class ThumbnailAdapter extends RecyclerView.Adapter<ThumbnailViewHolder> implements ThumbnailViewHolder.ThumbnailViewListener {

    public interface OnClickAdapterListener {

        void onClickThumbnail(String url);

        void onClickDelete(String url);
    }

    private ArrayList<String> arrayList;

    private OnClickAdapterListener mOnClickAdapterListener;

    public ThumbnailAdapter() {
        arrayList = new ArrayList<String>();
    }

    @Override
    public ThumbnailViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_thumbnail, parent, false);
        ThumbnailViewHolder viewHolder = new ThumbnailViewHolder(view);
        viewHolder.setThumbnailViewListener(this);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ThumbnailViewHolder holder, int position) {
        holder.setThumbnail(arrayList.get(position));
    }

    @Override
    public int getItemCount() {
        if (arrayList != null) {
            return arrayList.size();
        }
        return 0;
    }

    @Override
    public void onClickThumbnail(ThumbnailViewHolder holder) {
        if (mOnClickAdapterListener != null) {
            mOnClickAdapterListener.onClickThumbnail(arrayList.get(holder.getLayoutPosition()));
        }
    }

    @Override
    public void onClickDelete(ThumbnailViewHolder holder) {
        deleteThumbnail(holder.getLayoutPosition());
    }

    public void setOnClickAdapterListener(OnClickAdapterListener listener) {
        mOnClickAdapterListener = listener;
    }

    /**
     * 增加缩略图
     *
     * @param url 缩略图地址
     */
    public void addThumbnail(String url) {
        arrayList.add(url);
        notifyDataSetChanged();
    }

    /**
     * 获得缩略图地址数组
     *
     * @return 缩略图地址数组
     */
    public String[] getThumbnailUrlArray() {
        return arrayList.toArray(new String[arrayList.size()]);
    }

    /**
     * 获得缩略图数量
     *
     * @return 缩略图数量
     */
    public int getThumbnailLength() {
        return arrayList.size();
    }

    private void deleteThumbnail(int position) {
        if (mOnClickAdapterListener != null) {
            mOnClickAdapterListener.onClickDelete(arrayList.get(position));
        }
        arrayList.remove(position);
        notifyDataSetChanged();
    }
}
